"""
在线词典 ： 服务端逻辑处理
"""
from socket import *
from multiprocessing import Process
from dict_db import *


# 自定义进程类做事情
class Handle(Process):
    def __init__(self, conn):
        self.conn = conn
        self.db = DictData()  # 数据库处理对象
        super().__init__()

    # 总分结构：总体接收请求，分情况讨论
    def run(self):
        while True:
            request = self.conn.recv(128)
            print(request)
            # 分情况讨论

        self.db.close()
        self.conn.close()


# 开启网络
class DICTServer:
    def __init__(self, host="", port=0):
        self.host = host
        self.port = port
        self.address = (host, port)
        self.sock = self._create_socket()

    # 创建tcp套接字
    def _create_socket(self):
        sock = socket()
        sock.bind(self.address)
        return sock

    # 启动服务函数
    def serve_forever(self):
        self.sock.listen(5)
        print("Listen the port %d" % self.port)
        # 循环连接客户端
        while True:
            conn, addr = self.sock.accept()
            print("Connect from", addr)
            # 自定义进程类创建进程
            p = Handle(conn)
            p.start()


if __name__ == '__main__':
    dict = DICTServer(host="0.0.0.0", port=8888)
    dict.serve_forever()  # 启动服务
